import React, { useState, useEffect } from 'react';

const useKeyPress = () => {
  const [key, setKey] = useState(null);

  useEffect(() => {
    const handleKeyDown = (e) => {
      setKey(e.key);
    };

    const handleKeyUp = () => {
      setKey(null);
    };

    // 添加键盘按下和抬起的事件监听器
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  return key;
};

const KeyPressComponent = () => {
  const keyPressed = useKeyPress();

  return (
    <div>
      <p>当前按下的键是：{keyPressed}</p>
    </div>
  );
};

export default KeyPressComponent;
